package msa.ch03;

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import msa.ch03.data.StoredMessage;
import msa.ch03.displayable.FormMessageDetails;
import msa.ch03.displayable.ListMessages;
import msa.util.View;

public class MessageReceiverMidlet extends MIDlet implements View {
	
	public static final String COMMAND_EXIT = "COMMAND_EXIT";
	public static final String COMMAND_LIST = "COMMAND_LIST";
	public static final String COMMAND_DETAILS = "COMMAND_DETAILS";
	
	private final Display d;
	
	private final ListMessages list;
	private final FormMessageDetails details;
	
	private final MessageReceiver receiver;
	
	public MessageReceiverMidlet() {
		d = Display.getDisplay(this);
		list = new ListMessages(this);
		details = new FormMessageDetails(this);
		receiver = new MessageReceiver();
	}
	
	protected void destroyApp(boolean unconditional) {
		// Simply free all resources and let the application exit
		receiver.stop();
	}

	protected void pauseApp() {
		receiver.stop();
	}

	protected void startApp() throws MIDletStateChangeException {
		receiver.start();
		show(COMMAND_LIST);
	}

	public void show(String viewName) {
		if (COMMAND_EXIT.equals(viewName)) {
			destroyApp(true);
			notifyDestroyed();
		} else if (COMMAND_LIST.equals(viewName)) {
			d.setCurrent(list);
		} else {
			throw new RuntimeException("UNKNOWN COMMAND:" + viewName + " (no parms)");
		}
	}

	public void show(String viewName, Object parameter) {
		if (COMMAND_DETAILS.equals(viewName)) {
			StoredMessage message = (StoredMessage) parameter;
			details.loadMessage(message);
			d.setCurrent(details);
		} else {
			throw new RuntimeException("UNKNOWN COMMAND:" + viewName + " Parameter:" + parameter);
		}
	}

}
